package abg.core.service.chat.impl;

import abg.core.common.security.AuthUser;
import abg.core.common.security.AuthKit;
import abg.core.common.util.IdKit;
import abg.core.common.util.StringKit;
import abg.core.common.util.ThreadKit;
import abg.core.common.util.valid.Ids;
import abg.core.common.util.valid.base.Valid;
import abg.core.common.ws.handler.TextHandler;
import abg.core.domain.chat.ChatContentType;
import abg.core.domain.chat.ChatFriendMsgVo;
import abg.core.domain.chat.ChatGroupMsgVo;
import abg.core.domain.chat.ChatMsgListVo;
import abg.core.domain.db.*;
import abg.core.domain.search.Psh;
import abg.core.domain.sys.SRS;
import abg.core.domain.ws.WsPushType;
import abg.core.mapper.*;
import abg.core.service.chat.ChatFriendService;
import abg.core.service.chat.ChatMsgService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static abg.core.domain.db.table.ChatMsgLastTableDef.CHAT_MSG_LAST;
import static abg.core.domain.db.table.ChatMsgTableDef.CHAT_MSG;

@Slf4j
@Service
public class ChatMsgServiceImpl implements ChatMsgService {

    @Resource
    private ChatMsgMapper chatMsgMapper;

    @Resource
    private ChatGroupMapper chatGroupMapper;

    @Resource
    private ChatGroupUserMapper chatGroupUserMapper;

    @Resource
    private ChatMsgLastMapper chatMsgLastMapper;

    @Resource
    private ChatFriendService chatFriendService;

    @Resource
    private SysUserMapper userMapper;

    //用户拉取最后消息列表
    @Override
    public List<ChatMsgListVo> chatMsgLastList() {
        AuthUser authUser = AuthKit.mastLogin();

        //所有最后一条消息
        String currentUserId = authUser.getUserId();
        QueryWrapper wrapper = QueryWrapper.create()
                .select(CHAT_MSG.ALL_COLUMNS, CHAT_MSG_LAST.IS_TOP)
                .leftJoin(CHAT_MSG).on(CHAT_MSG.ID.eq(CHAT_MSG_LAST.CHAT_MSG_ID))
                .and(CHAT_MSG_LAST.SEND_USER_ID.eq(currentUserId))
                .or(CHAT_MSG_LAST.RECEIVE_USER_ID.eq(currentUserId))
                .orderBy(CHAT_MSG_LAST.IS_TOP.desc(), CHAT_MSG.CT.desc());
        List<ChatMsgListVo> chatMsgLasts = chatMsgLastMapper.selectListByQueryAs(wrapper, ChatMsgListVo.class);

        //补充信息
        for (ChatMsgListVo chatMsg : chatMsgLasts) {
            String chatType = chatMsg.getChatType();

            //发送人信息
            String sendUserId = chatMsg.getSendUserId();
            SysUser sendUser = userMapper.selectColumnById(sendUserId, "nick_name", "avatar");
            chatMsg.setSendUserName(sendUser.getNickName());
            chatMsg.setSendUserAvatar(sendUser.getAvatar());


            //私聊
            if ("0".equals(chatType)) {
                //接收人信息
                String receiveUserId = chatMsg.getReceiveUserId();
                SysUser receiveUser = userMapper.selectColumnById(receiveUserId, "nick_name", "avatar");
                chatMsg.setReceiveUserName(receiveUser.getNickName());
                chatMsg.setReceiveUserAvatar(receiveUser.getAvatar());
            }

            //群聊
            if ("1".equals(chatType)) {
                //发送群信息
                String groupId = chatMsg.getGroupId();
                //查 群昵称
                ChatGroup chatGroup = chatGroupMapper.selectColumnById(groupId, "group_name");
                String groupName = chatGroup.getGroupName();
                //查 ，自定义群昵称
                ChatGroupUser groupUser = chatGroupUserMapper.getColumnByUserIdAndGroupId(currentUserId, groupId, "group_nick_name");
                //设置群名
                chatMsg.setGroupName(groupName);
                if (groupUser != null && StringKit.isNotBlank(groupUser.getGroupNickName())) {
                    chatMsg.setGroupName(groupUser.getGroupNickName());
                }

                //设置群头像
                String groupAvatar = "";
                List<ChatGroupUser> groupUser9 = chatGroupUserMapper.getColumnLimitById(groupId, 9, "user_id");
                ArrayList<String> avatarList = new ArrayList<>(groupUser9.size());
                for (ChatGroupUser chatGroupUser : groupUser9) {
                    String userId = chatGroupUser.getUserId();
                    SysUser sysUser = userMapper.selectColumnById(userId, "avatar");
                    avatarList.add(sysUser.getAvatar());
                }
                groupAvatar = StringKit.join(avatarList);
                chatMsg.setGroupAvatar(groupAvatar);
            }

        }

        return chatMsgLasts;
    }

    //获取指定朋友聊天记录
    @Override
    public Page<ChatFriendMsgVo> friendMsgPage(Psh psh, String friendUserId) {
        AuthUser authUser = AuthKit.mastLogin();
        QueryWrapper wrapper = QueryWrapper.create().eq("chat_type", "0").
                and(CHAT_MSG.SEND_USER_ID.eq(authUser.getUserId()).and(CHAT_MSG.RECEIVE_USER_ID.eq(friendUserId)))
                .or(CHAT_MSG.SEND_USER_ID.eq(friendUserId).and(CHAT_MSG.RECEIVE_USER_ID.eq(authUser.getUserId())));
        Page paginate = chatMsgMapper.paginate(psh, wrapper);

        return paginate;
    }

    //获取指定群的聊天记录
    @Override
    public Page<ChatGroupMsgVo> groupMsgPage(String groupId) {
        return null;
    }

    /**
     * 设置消息状态为已读
     *
     * @param chatIds 主键ID
     */
    @Valid
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean msgRead(@Ids String chatIds) {
        AuthUser authUser = AuthKit.mastLogin();

        //TODO 设置消息状态为 对方已读

        return true;
    }

    /**
     * 用户，发送消息给用户
     *
     * @param param 消息体
     * @see ChatContentType  消息类型
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendChatMsg(ChatMsg param) {
        AuthUser authUser = AuthKit.mastLogin();
        String currentUserId = authUser.getUserId();

        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setId(IdKit.getId());
        chatMsg.setSendUserId(currentUserId);
        chatMsg.setSendTime(LocalDateTime.now());
        chatMsg.setContent(param.getContent());
        chatMsg.setContentType(param.getContentType());

        String chatType = param.getChatType();
        chatMsg.setChatType(chatType);
        //群聊

        //私聊
        if ("0".equals(chatType)) {
            chatMsg.setReceiveUserId(param.getReceiveUserId());
        }

        //记录消息入库
        chatMsgMapper.insertSelective(chatMsg);

        updateChatMsgLast(chatMsg.id);

        //发送通知
        ThreadKit.getPool().execute(() -> {
            //私聊:通知用户拉取信息
            if ("0".equals(chatType)) {
                wsNoticeUserGetMsg(currentUserId, param.getReceiveUserId());
            }

            //群聊:通知用户拉取信息
            if ("1".equals(chatType)) {
                String groupId = param.getGroupId();
                List<ChatGroupUser> groupUsers = chatGroupUserMapper.getColumnListByKey("group_id", groupId, "user_id");
                for (ChatGroupUser chatGroupUser : groupUsers) {
                    wsNoticeUserGetMsg(currentUserId, chatGroupUser.getUserId());
                }
            }
        });

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateChatMsgLast(String chatMsgId) {
        ChatMsg chatMsg = chatMsgMapper.selectOneById(chatMsgId);
        if (chatMsg == null) return false;
        String chatType = chatMsg.getChatType();

        //私聊
        if ("0".equals(chatType)) {
            String sendUserId = chatMsg.getSendUserId();
            String receiveUserId = chatMsg.getReceiveUserId();
            QueryWrapper eq = QueryWrapper.create().eq("send_user_id", sendUserId).eq("receive_user_id", receiveUserId);
            ChatMsgLast chatMsgLast = chatMsgLastMapper.selectOneByQuery(eq);
            if (chatMsgLast == null) {
                chatMsgLast = new ChatMsgLast();
                chatMsgLast.setChatMsgId(chatMsgId);
                chatMsgLast.setSendUserId(sendUserId);
                chatMsgLast.setReceiveUserId(receiveUserId);
                chatMsgLast.setUt(chatMsg.getSendTime());
                chatMsgLastMapper.insertSelective(chatMsgLast);
            } else {
                chatMsgLast.setChatMsgId(chatMsgId);
                chatMsgLast.setUt(chatMsg.getSendTime());
                chatMsgLastMapper.updateByQuery(chatMsgLast, eq);
            }
            return true;
        }
        //群聊

//        chatMsg.getSendUserId();
//        chatMsg.setReceiveUserId();
        if (chatMsg != null) {

        }

        return true;
    }


    /**
     * 通知用户需要拉取消息
     *
     * @param receiveUserId 通知用户ID
     */
    @Override
    public boolean wsNoticeUserGetMsg(String sendUserId, String receiveUserId) {
        SRS<Object> result = SRS.bySuccess();
        result.set("wsPushType", WsPushType.CHAT_GET_MSG);
        result.set("sendUserId", sendUserId);
        result.set("receiveUserId", receiveUserId);
        Channel channel = TextHandler.channelPhoneAll.get("PHONE" + receiveUserId);
        if (channel != null) {
            channel.writeAndFlush(new TextWebSocketFrame(result.toJSONString()));
        }
        return true;
    }

}
